<template>
  <div class="mod-prod prod-list-mod">
    <div style="margin-bottom: 10px">
      <el-button
        type="text"
        icon="ArrowLeftBold"
        @click="onBack"
      >
        返回
      </el-button>
    </div>

    <el-descriptions :column="4">
      <el-descriptions-item label="询价单号">
        {{ basicInfo.orderNo || '--' }}
        <hm-copy :text="basicInfo.orderNo" />
      </el-descriptions-item>
      <el-descriptions-item label="询价时间">
        {{ basicInfo.inquiryTime || '--' }}
      </el-descriptions-item>
      <el-descriptions-item label="结束时间">
        {{ basicInfo.updatedTime || '--' }}
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag size="small">
          {{ statusList[basicInfo.status] }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="询价客户">
        {{ basicInfo.merchantName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item label="询价人">
        {{ basicInfo.createdBy || '--' }}
      </el-descriptions-item>
      <el-descriptions-item label="报价总金额">
        {{ moneyFormat(basicInfo.totalPrice) }}
      </el-descriptions-item>
      <el-descriptions-item label="最长交期">
        {{ basicInfo.tradeTerm === 0 ? '现货' : basicInfo.tradeTerm ? `${basicInfo.tradeTerm}日发货` : '--' }}
      </el-descriptions-item>
    </el-descriptions>

    <div
      v-if="activeName == 1"
      class="operation-bar"
    >
      <el-button
        v-if="isAuth('self:inquiry:quote') && canSure"
        type="primary"
        @click="onQuote"
      >
        {{ canComplete && isCompleted ? '完成报价' : '更新报价' }}
      </el-button>
    </div>

    <!-- 主体内容 -->
    <div class="main-container">
      <el-tabs v-model="activeName">
        <el-tab-pane
          label="可询价"
          name="1"
        >
          <!-- 表格 -->
          <div class="table-con prod-table">
            <el-table
              ref="prodListTableRef"
              :data="dataList"
              header-cell-class-name="table-header"
              row-class-name="table-row"
              style="width: 100%"
              default-expand-all
            >
              <el-table-column
                type="expand"
                style="padding: 10px;"
              >
                <template #default="scope">
                  <inquiryDetail
                    :sub-order-no="scope.row.subOrderNo"
                    :shop-id="scope.row.shopId"
                    :status="scope.row.status"
                    @refresh="init"
                  />
                </template>
              </el-table-column>

              <el-table-column
                prop="subOrderNo"
                label="子询价单号"
                show-overflow-tooltip
                min-width="150"
              />

              <el-table-column
                prop="merchantShotName"
                label="品牌信息"
                min-width="150"
              />

              <el-table-column
                prop="merchantName"
                label="企业信息"
                min-width="150"
              />

              <el-table-column
                prop="shopUserMobile"
                label="商城管理员"
                min-width="150"
              />

              <el-table-column
                prop="status"
                label="状态"
                :width="100"
              >
                <template #default="scope">
                  {{ statusList[scope.row.status] || '--' }}
                </template>
              </el-table-column>

              <!-- <el-table-column
                fixed="right"
                align="center"
                :label="$t('publics.operating')"
                width="150"
              >
                <template #default="scope">
                  <div class="text-btn-con">
                    <div
                      v-if="isAuth('self:inquiry:quote') && scope.row.status == 10"
                      class="default-btn text-btn"
                      @click="onSetPrice(scope.row)"
                    >
                      修改报价
                    </div>
                    <div
                      class="default-btn text-btn"
                      @click="onView(scope.row)"
                    >
                      详情
                    </div>
                  </div>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <!-- 分页 -->
          <!-- <el-pagination
            v-if="dataList.length"
            :current-page="page.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="onPageSizeChange"
            @current-change="onPageChange"
          /> -->
        </el-tab-pane>
        <el-tab-pane
          label="不可询价"
          name="2"
        >
          <can-not-inquiry-detail
            v-if="activeName == 2"
            ref="canNotInquiryDetailRef"
            :order-no="orderNo"
            @refresh="init"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      v-model="visible"
      :width="1000"
      :close-on-click-modal="false"
      title="子询价单详情"
    >
      <div
        ref="closepopoverRef"
        class="table-con prod-table"
      >
        <el-table
          :data="detailList"
          style="width: 100%"
        >
          <el-table-column
            prop="prodName"
            label="商品名称"
            show-overflow-tooltip
            min-width="150"
          >
            <template #default="scope">
              <el-tooltip
                v-if="getTip(scope.row)"
                effect="dark"
                :content="getTip(scope.row)"
                placement="bottom-start"
              >
                <el-icon style="color: red">
                  <Warning />
                </el-icon>
              </el-tooltip>
              {{ scope.row.prodName }}
            </template>
          </el-table-column>

          <el-table-column
            prop="skuCode"
            label="型号"
            min-width="150"
          >
            <template #default="scope">
              <el-button
                type="text"
                @click="goToPrice(scope.row)"
              >
                {{ scope.row.skuCode }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column
            prop="tradeTerm"
            label="交期"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.tradeTerm === 0 ? '现货' : scope.row.tradeTerm ? `${scope.row.tradeTerm}日发货` : (scope.row.status == 5 && scope.row.invalidFlag != 1 ? '信息更新中' : '--') }}
            </template>
          </el-table-column>

          <el-table-column
            prop="stocks"
            label="库存"
            min-width="100"
          >
            <template #default="scope">
              {{ scope.row.stocks || (scope.row.status == 5 && scope.row.invalidFlag != 1 ? '信息更新中' : '--') }}
            </template>
          </el-table-column>

          <el-table-column
            prop="number"
            label="数量"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.number || (scope.row.status == 5 && scope.row.invalidFlag != 1 ? '信息更新中' : '--') }}
            </template>
          </el-table-column>

          <el-table-column
            prop="price"
            label="单价(￥/个)"
            :width="140"
          >
            <template #default="scope">
              <div style="display: flex; justify-content: space-between;">
                <span>
                  {{ scope.row.price || (scope.row.status == 5 && scope.row.invalidFlag != 1 ? '信息更新中' : '--') }}
                </span>
                <el-popover
                  placement="bottom"
                  trigger="click"
                  :width="175"
                  @show="() => {
                    onePrice = scope.row.price || ''
                  }"
                >
                  <div class="popover-box">
                    <div>
                      <el-input-number
                        v-model="onePrice"
                        :min="0"
                        :max="1000000000"
                        @change="(currentValue, oldValue) => {
                          // scope.row.totalPrice = currentValue * (scope.row.number || 0)
                        }"
                      />
                    </div>
                    <div style="margin-top: 10px;">
                      <el-button
                        @click="closePopover()"
                      >
                        取消
                      </el-button>
                      <el-button
                        type="primary"
                        @click="handleChange(scope.row)"
                      >
                        保存
                      </el-button>
                    </div>
                  </div>
                  <template #reference>
                    <el-icon
                      v-if="isEditing"
                      color="#409efc"
                    >
                      <EditPen />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="totalPrice"
            label="总价(￥)"
            :width="100"
          >
            <template #default="scope">
              {{ scope.row.totalPrice || (scope.row.status == 5 && scope.row.invalidFlag != 1 ? '信息更新中' : '--') }}
            </template>
          </el-table-column>

          <el-table-column
            prop="buyerRemark"
            label="客户备注"
            show-overflow-tooltip
            :width="150"
          >
            <template #default="scope">
              {{ scope.row.buyerRemark || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="sellerRemark"
            label="商家备注"
            show-overflow-tooltip
            :width="150"
          >
            <template #default="scope">
              {{ scope.row.sellerRemark || '--' }}
            </template>
          </el-table-column>

          <el-table-column
            v-if="!isEditing"
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="100"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onViewProd(scope.row)"
                >
                  查看
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="detailList.length"
        style="margin-top: 10px"
        :current-page="detailPage.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="detailPage.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="detailPage.total"
        @size-change="onPageSizeChangeD"
        @current-change="onPageChangeD"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'
import { statusList } from './eum.js'
import inquiryDetail from '../components/inquiry-detail.vue'
import canNotInquiryDetail from '../components/can-not-inquiry-detail.vue'

const getTip = ({ invalidFlag, status, validStatus }) => {
  if (status == 7) {
    return '报价已过期'
  }
  if (status == 8) {
    return '该询价单已被取消'
  }
  if (validStatus != 0) {
    return '该商品已失效'
  }
  if (invalidFlag == 1) {
    return '该询价单已被商家设为无效商品'
  }
  return ''
}

const activeName = ref('1')

let shopId = ''
let subOrderNo = ''
const visible = ref(false)
const isEditing = ref(false)
const onePrice = ref(0)
const onSetPrice = (row) => {
  isEditing.value = true
  visible.value = true
  shopId = row.shopId
  subOrderNo = row.subOrderNo
  getDetailList(detailPage, subOrderNo)
}

const closepopoverRef = ref()
// 关闭popover弹窗
const closePopover = () => {
  closepopoverRef.value.click()
}

const handleChange = (row) => {
  http({
    url: http.adornUrl('/shop/inquiryListItem'),
    method: 'put',
    data: {
      price: onePrice.value,
      id: row.id
    }
  }).then(() => {
    ElMessage.success('操作成功')
    closePopover()
    getDetailList(detailPage, row.subOrderNo)
  })
}

let tempSearchForm = null // 保存上次点击查询的请求条件

const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 9999 // 每页显示多少条
})

const detailPage = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const orderNo = ref('')
const route = useRoute()
onMounted(() => {
  init()
})

const canNotInquiryDetailRef = ref(null)
const init = (data) => {
  orderNo.value = data?.orderNo || route.query.orderNo
  activeName.value = '1'
  dataList.value = []
  getBasicInfo()
  // if (activeName.value == 2) {
  //   canNotInquiryDetailRef.value?.init()
  // }
}

const isCompleted = ref(false)
const getAllDetailList = () => {
  const params = {
    orderNo: orderNo.value,
    current: 1,
    size: 9999
  }
  http({
    url: http.adornUrl('/shop/inquiryListItem/page'),
    method: 'get',
    params: http.adornParams(params)
  }).then(({ data }) => {
    const emptyData = (data.records || []).filter(d => (d.price === null) || (d.stocks === null) || (d.tradeTerm === null) || (d.totalPrice === null) || (d.number === null))
    isCompleted.value = !emptyData.length
  })
}

const canSure = ref(false)
const canComplete = ref(false)
const checkCanSure = () => {
  http({
    url: http.adornUrl('/shop/subInquiryList/checkButton'),
    method: 'post',
    params: http.adornParams({
      orderNo: basicInfo.value.orderNo
    })
  }).then(res => {
    const { checkButton, hasNotSelfShopInquirying } = res.data || {}
    canSure.value = checkButton == 1
    canComplete.value = hasNotSelfShopInquirying != 1
  })
}

const router = useRouter()
const onBack = () => {
  const { page, search, status } = route.query
  router.replace({
    path: '/self/inquiry/index',
    query: { page, search, status }
  })
}

const basicInfo = ref({})
const getBasicInfo = () => {
  http({
    url: http.adornUrl(`/shop/inquiryList/info/${orderNo.value}`),
    method: 'get',
    params: http.adornParams({})
  }).then(res => {
    basicInfo.value = res.data || {}
    getDataList(page)
    checkCanSure()
    getAllDetailList()
  })
}

const getDataList = (pageParam) => {
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = (page.currentPage > size ? size : page.currentPage) || 1
  }
  tempSearchForm = {
    orderNo: basicInfo.value.orderNo,
    current: pageParam == null ? page.currentPage : pageParam.currentPage,
    size: pageParam == null ? page.pageSize : pageParam.pageSize
  }
  http({
    url: http.adornUrl('/shop/subInquiryList/page'),
    method: 'get',
    params: http.adornParams(tempSearchForm)
  }).then(({ data }) => {
    dataList.value = data.records || []
    page.total = data.total
    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

const detailList = ref([])
const onView = (row) => {
  visible.value = true
  isEditing.value = false
  shopId = row.shopId
  subOrderNo = row.subOrderNo
  getDetailList(detailPage, subOrderNo)
}

const onQuote = () => {
  const fn = () => {
    http({
      url: http.adornUrl('/shop/subInquiryList/confirm'),
      method: 'post',
      params: http.adornParams({
        orderNo: basicInfo.value.orderNo
      })
    }).then(() => {
      ElMessage.success('操作成功')
      getBasicInfo()
    })
  }
  if (canComplete.value) {
    ElMessageBox.confirm('完成报价后所有商品的报价将不可修改,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      fn()
    })
  } else {
    fn()
  }
}

const getDetailList = (pageParam, subOrderNo) => {
  const params = {
    subOrderNo,
    current: pageParam == null ? detailPage.currentPage : pageParam.currentPage,
    size: pageParam == null ? detailPage.pageSize : pageParam.pageSize
  }
  http({
    url: http.adornUrl('/shop/inquiryListItem/page'),
    method: 'get',
    params: http.adornParams(params)
  }).then(({ data }) => {
    detailList.value = (data.records || [])
    detailPage.total = data.total
    // 末尾页数据为空重新请求
    if (!detailList.value.length && detailPage.currentPage > 1) {
      detailPage.currentPage = 1
      getDetailList(detailPage, subOrderNo)
    }
  })
}

const onViewProd = (row) => {
  const url = import.meta.env.VITE_APP_SHOP_ADDRESS
  window.open(`${url}detail?prodId=${row.prodId}`)
}

const goToPrice = (row) => {
  const { prodId, skuCode } = row
  // 检查是否自营
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(0, 0, 0, 0.7)'
  })
  http({
    url: http.adornUrl(`/prod/prod/info/${prodId}`),
    method: 'get',
    params: http.adornParams({})
  }).then(({ data }) => {
    if (data.selfProduct == 1) {
      router.push({
        path: '/self/price-manage/price',
        query: { prodId, shopId, skuCode }
      })
    } else {
      ElMessage.warning('非自营商品')
    }
  }).finally(() => {
    loading.close()
  })
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}
const onPageSizeChangeD = (val) => {
  detailPage.pageSize = val
  getDetailList(detailPage, subOrderNo)
}
const onPageChangeD = (val) => {
  detailPage.currentPage = val
  getDetailList(detailPage, subOrderNo)
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>

</style>
